// stores/projectStore.ts
import { defineStore } from 'pinia';
import { ref } from 'vue';
import {initialEdges, initialNodes} from '../components/data/initial-elements';
import {useServer} from '@/components/ts/useServer';
import {useUserStore} from '@/stores/userStore';
import type { Node, Edge } from '@vue-flow/core';
import { formatDateTimeCN} from '../utils/DataTime.js';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';

export const useProjectsStore = defineStore('projects', () => {
  // 存储所有个人Project页面
    const projects = ref<{ id: string, name: string,createdAt?:string,updatedAt?:string, is_opened?:boolean, content: {initialNodes:Node<any, any,string>[], initialEdges:Edge<any, any,string>[]}, loaded?: boolean, description?: string, thumbnail?: string,  isPublic?: boolean, authorName?: string|null, authorID?: string, teamName?: string, teamID?: string, favorites?: number,}[]>([]);
    const allprojects=ref<{ userID: string,projectID:string, projectName: string,createdAt?:string,updatedAt?:string, is_opened?:boolean, content: {initialNodes:Node<any, any,string>[], initialEdges:Edge<any, any,string>[]}, loaded?: boolean, description?: string, thumbnail?: string,  isPublic?: boolean, authorName?: string, authorID?: string, teamName?: string, teamID?: string, favorites?: number,}[]>([]);
    
    // 当前选中的Project
    const currentProjectId = ref<string | null>(null);
    const templepj = {
        projectName: '',
        authorName: '',
        authorID: '',
        thumbnail: '',
        teamName: '',
        teamID: '',
        content: { initialNodes: [], initialEdges: [] },
        loaded: true,
        is_opened: false,
        isPublic: false,
        createdAt: formatDateTimeCN(),
        updatedAt: formatDateTimeCN(),
        description: '',
        favorites: 0,
    }
    const templepj1={
        id:'',
        name: '',
        authorName: '',
        authorID: '',
        thumbnail: '',
        teamName: '',
        teamID: '',
        content: { initialNodes: [], initialEdges: [] },
        loaded: true,
        is_opened: false,
        isPublic: false,
        createdAt: formatDateTimeCN(),
        updatedAt: formatDateTimeCN(),
        description: '',
        favorites: 0,
    }
    const {get, post, postWithCallback } = useServer();
    const userStore = useUserStore();
    const router = useRouter();
    
    // 初始化方法
    const initializeProjects = async () => {

        try {
            const response = await post('fetchUserEditingProjects', { userID: userStore.currentUser });
            //console.log('initializeProjects', response.projects)
            let validpj = response.projects.filter(
                 (p: any)  =>p&& p.projectID && p.content && Object.keys(p.content).length > 0
            );//排除content={}
            //console.log('validpj', validpj)
            projects.value = validpj.map((project: any) => {
                let i={...templepj1,...project,name:project.projectName,id:project.projectID};
                delete i.projectName;
                delete i.projectID;
                if(!i.authorName) i.authorName=userStore.currentUserName;
                if(!i.authorID) i.authorID=userStore.currentUser;
                return i
            })
            console.log('initializePersonalProjects', projects.value)
        } catch (error) {
            console.error('Failed to fetch projects:', error);
        }
    };
    const fetchAllProjects = async () => {
        const response = await get('fetchAllProjects');
        console.log('fetchAllProjects', response)
        if (response.success) {
            allprojects.value = response.projects.filter(
                (p: any) => p && p.projectID && p.content && Object.keys(p.content).length > 0
            );//排除content={}
        }else{
            console.error('Failed to fetch projects:', response);
        }
    }
    //按需更新project信息
    const updatepjinfo = async (
        project_ID: string,
        pj: any, userID?: string, isoverwrite = true) => {
        let user_id = userID ? userID : userStore.currentUser;
        let pro = projects.value.find(p => p.id === project_ID)
        let tim = formatDateTimeCN();
        if (isoverwrite) {
            if (!pro) return false;
            let i = { ...templepj, ...pro, ...pj, updatedAt: tim };
            let { id, name, ...tmp } = i;
            tmp.projectName = name;
            //console.log('tmp:',tmp)

            const res = await post('saveUserProject', {
                userID: user_id,
                projectID: project_ID,
                content: tmp,
            });

            pro.updatedAt = tim;
            return pro;
        } else {
            //更新其他用户的project信息
            let i = { ...pj, updatedAt: tim };
            // console.log('info:', {
            //     userID: user_id,
            //     projectID: project_ID,
            //     ...i
            // })
            const res = await post('saveAllUserProject', {
                user_id: user_id,
                projectID: project_ID,
                ...i
            });
            return i
        }
    }

    // 更新项目名称的方法
    const updateProjectName = (projectId: string, newName: string) => {
        let project = projects.value.find(p => p.id === projectId);
        if (project) {
            project.name = newName;
            updatepjinfo(projectId, { name: newName});
        }
    };
    
    // 添加一个新的Project
    const addProject = (name: string,description: string, content: { initialNodes: Node<any, any, string>[], initialEdges: Edge<any, any, string>[] },user_ID?:string) => {
        let id = 'project_' + Date.now()
        const newProject = {...templepj1,...{id: id,name: name, content: content, updatedAt: formatDateTimeCN(),is_opened:true,authorName:userStore.currentUserName,authorID:userStore.currentUser,description:description||''  } };
        let tp={ ...templepj,...{content: content,projectName:name, updatedAt: formatDateTimeCN(),is_opened:true,authorName:userStore.currentUserName,authorID:userStore.currentUser,description:description||'' } }
        console.log('addProject', tp)
        postWithCallback('saveUserProject', {
            userID: user_ID?user_ID:userStore.currentUser,
            projectID: id,
            content: tp,
        }, (res) => {
            if (res.success) {
                console.log('Adding Success')
                newProject.is_opened = true;
                projects.value.push(newProject as any);
                currentProjectId.value = id;//触发更新
            }
            else {
                console.log('Saving Failed')
            }
        })
    };
    // 关闭Project标签
    const removeProject = async (id: string) => {
        let pj = await updatepjinfo(id, { is_opened: false });
        if (pj) {
            console.log('Close Success')
            pj.is_opened = false;
            if (currentProjectId.value === id)
                currentProjectId.value = null;//安全刷新
        }
    };

    // 设置当前选中的Project
    const setCurrentProject = (id: string) => {
        console.log('setCurrentProject', id);
        currentProjectId.value = id;
    };

    let timer: any | null = null;
    let forceTimer: any | null = null;
    let forcing:boolean = false;
    const updateInterval = 3000; // 3秒内不被调用则更新
    const forceUpdateInterval = 10000; // 每10秒强制更新一次

    // 模拟网络更新函数
    const networkUpdate = (projectID:string) => {
        let pj=projects.value.find(p => p.id === projectID);
        if (!pj) return false;
        let tmp_content={content: pj.content};
        updatepjinfo(projectID, tmp_content);
       // console.log("NetworkUpdate content Success:",tmp_content)
    };
    // 更新Projecth画板容
    const updateProjectContent = (
        id: string, content: {initialNodes:Node<any, any,string>[], initialEdges:Edge<any, any,string>[]}, atOnce:boolean=false) => {
        const project = projects.value.find(p => p.id === id);
        if (project) {
            project.content = content;
            networkUpdate(id);
        }
        return

        if (atOnce){
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            if (forceTimer) {
                clearTimeout(forceTimer);
                forceTimer = null;
            }
            networkUpdate(id);
            forcing = false;
            return
        }
        // 缓冲网络更新
        if (timer) {
            clearTimeout(timer);
        }
        // 设置新的定时器
        timer = setTimeout(() => {
            networkUpdate(id);
        }, updateInterval);
        // 每10秒强制触发一次网络更新
        if(forcing){
            return;
        }
        forceTimer = setTimeout(() => {
            networkUpdate(id);
            forcing = false;
        }, forceUpdateInterval);
        forcing = true;
    };
    // 删除Project
    const deleteProject = (id: string) => {
        const project = projects.value.find(p => p.id === id);
        if (!project) {
            return;
        }
        //暂时使用清空内容的方式
        postWithCallback('saveUserProject', { userID: userStore.currentUser, projectID: id, content: {} }, (res) => {
            if (res.success) {
                console.log('Deleting Success')
                projects.value = projects.value.filter(p => p.id !== id);
            }
            else {
                console.log('Deleting Failed')
            }
            //removeProject(id);
        })
        // post('deleteUserProject', { userID: userStore.currentUser,authorID:project.authorID, project_ID: id }).then(res => {
        //     if (res.success) {
        //         message.info("You have just deleted the project: " + project.name)
        //         projects.value = projects.value.filter(p => p.id !== id);
        //     }
        //     else {
        //         console.log('Deleting Failed',res)
        //     }
        // })
    }

    // 复制一个Project
    const copyProject = (id: string) => {
        const projectToCopy = projects.value.find(p => p.id === id);
        if (projectToCopy) {
            addProject(`${projectToCopy.name} (Copy)`, projectToCopy.content);
        }
    };

    const star = (pj: any) => {
        let pid = pj.projectID;
        let uid = pj.userID;
        const starProject = userStore.star_projects.find(project => project.userID === uid && project.projectID === pid);
        const pro = allprojects.value.find(p => p.projectID === pid && p.userID === uid);
        if (!pro) return;
        if (starProject) {
            //当前已收藏，取消收藏
            starProject.is_star = false;
            if (pro.favorites == null) {
                pro.favorites = 0;
            } else {
                pro.favorites = Math.max(0, pro.favorites - 1);
            }
            updatepjinfo(starProject.projectID, { favorites: pro.favorites }, starProject.userID, false);
            userStore.star_projects = userStore.star_projects.filter(project => project.userID !== starProject.userID && project.projectID !== starProject.projectID);
        } else {
            if (pro.favorites == null) {
                pro.favorites = 1;
            } else {
                pro.favorites++;
            }
            userStore.star_projects.push({
                "starID": "star_" + Math.floor(
                    Math.random() * (9999999999999 - 1000000000000 + 1)
                    + 1000000000000
                ),
                "userID": uid,
                "projectID": pid,
                "description": pro?.description ?? "",
                "favorites": pro.favorites,
                "projectName": pro?.projectName ?? "",
                "staredAt": formatDateTimeCN(new Date()),
                "is_star": true
            });

            console.log('pro:', pro)
            updatepjinfo(pid, { favorites: pro?.favorites ?? 0 }, uid, false);
        }
        post('user/updateUserInfo', { userID: userStore.currentUser, star_projects: userStore.star_projects }).then(res => {
            if (res.success) {
                console.log('操作成功')
            } else {
                console.log('操作失败')
            }
        });
    }

    const isStarred = (userID: string, projectID: string) => {
    //console.log("userStore.star_projects:",userStore.star_projects);
    return userStore.star_projects.find(project => project.userID === userID && project.projectID === projectID)?.is_star;
  }

  const star_pj=(starID:string)=>{
    let flag=false
    userStore.star_projects.forEach(item=>{
        if(item.starID===starID){
            item.is_star=!item.is_star
            flag=item.is_star   
            if(flag){
                item.favorites++
            }else{
                item.favorites=Math.max(0,item.favorites-1)
            }
            updatepjinfo(item.projectID, { favorites: item.favorites }, item.userID, false);
        }
    })
    let isStarred=userStore.star_projects.filter(item=>item.is_star===true)
    post('user/updateUserInfo', { userID: userStore.currentUser,star_projects:isStarred }).then(res => {
        if (res.success) {
            if(flag){
                message.success('收藏成功')
            }else{
                message.success('取消收藏')
            }
        } else {
            message.error('操作失败')
        }
    });
}

    const visit_pj = (targetID: string,authorID:string,visitorID?:string,visitorName?:string) => {
        let pj=allprojects.value.find(item=>item.projectID===targetID)
        if(!pj){
            console.log('项目不存在')
            return
        }
        // console.log('visitorID:',visitorID)
        // console.log('userStore.currentUser:',userStore.currentUser)
        if (visitorID === authorID) {
            message.info('Are you sure you want to visit your own project?')
            return
        }
        localStorage.setItem(targetID, JSON.stringify(pj));
        const routeUrl = router.resolve({
            name: 'ProjectPreview',
            params: { id: targetID,visitorID:visitorID??userStore.currentUser,visitorName:visitorName??userStore.currentUserName }
        });
        window.open(routeUrl.href, '_blank');
    }
    const open_project =async (id: string) => {
  let pj = projects.value.find(project => project.id === id);//find返回的是对象引用
  if (pj) {
    let res=await updatepjinfo(pj.id, {
      is_opened: true,
    });
      console.log('Open Success')
      pj.is_opened = true;
      setCurrentProject(id);
      router.push('/flow');
  }
}
const getNode=(nid:string,pid?:string)=>{
    let tmp_pid=pid??currentProjectId.value
    let pj=projects.value.find(item=>item.id===tmp_pid)
    if(!pj){
        console.log('项目不存在')
        return
    }
    return pj.content.initialNodes.find(item=>item.id===nid)
}

const updateNodeContent=(nid:string,data:any,pid?:string)=>{
    let tmp_pid=<string>pid??currentProjectId.value
    console.log('tmp_pid:',tmp_pid)
    let pj=projects.value.find(item=>item.id===tmp_pid)
    if(!pj){
        console.log('项目不存在')
        return
    }
    let node=pj.content.initialNodes.find(item=>item.id===nid)
    if(!node){
        console.log('节点不存在')
        return
    }
    node={...node,...data}
    console.log('更新节点内容:',pj.content.initialNodes)
    updatepjinfo(tmp_pid,{});
}

    return {
        projects,
        currentProjectId,
        addProject,
        removeProject,
        deleteProject,
        setCurrentProject,
        updateProjectContent,
        copyProject,
        updateProjectName,
        initializeProjects,
        updatepjinfo,
        fetchAllProjects,
        allprojects,
        star,
        isStarred,
        star_pj,
        visit_pj,
        open_project,
        networkUpdate,
        getNode,
        updateNodeContent
    };
});
